package com.qiniuyun.threedgenerator.util;

import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

// SimpleModelValidator.java
@Component
public class SimpleModelValidator {

    private static final Set<String> SUPPORTED_MODEL_FORMATS = Set.of(
            "obj", "stl", "gltf", "glb", "ply"
    );

    private static final Map<String, String> MODEL_MIME_TYPES = Map.of(
            "obj", "text/plain",
            "stl", "application/sla",
            "gltf", "model/gltf+json",
            "glb", "model/gltf-binary",
            "ply", "text/plain"
    );

    /**
     * 验证模型文件格式是否支持
     */
    public boolean isValidModelFormat(String filename) {
        if (filename == null) return false;

        String extension = getFileExtension(filename).toLowerCase();
        return SUPPORTED_MODEL_FORMATS.contains(extension);
    }

    /**
     * 获取模型的MIME类型
     */
    public String getModelMimeType(String filename) {
        String extension = getFileExtension(filename).toLowerCase();
        return MODEL_MIME_TYPES.getOrDefault(extension, "application/octet-stream");
    }

    /**
     * 简单的模型文件头验证
     */
    public boolean isValidModelFile(File file) {
        try {
            byte[] header = new byte[100];
            try (FileInputStream fis = new FileInputStream(file)) {
                int bytesRead = fis.read(header);
                if (bytesRead < 5) return false;

                String headerStr = new String(header, 0, bytesRead);
                String filename = file.getName().toLowerCase();

                // 简单的格式识别
                if (filename.endsWith(".obj")) {
                    return headerStr.contains("v ") && headerStr.contains("f ");
                } else if (filename.endsWith(".stl")) {
                    return headerStr.contains("solid") || isBinaryStl(header);
                } else if (filename.endsWith(".gltf")) {
                    return headerStr.trim().startsWith("{");
                }

                return true; // 对于其他格式，暂时信任文件扩展名
            }
        } catch (IOException e) {
            return false;
        }
    }

    private boolean isBinaryStl(byte[] header) {
        // 简单的二进制STL文件识别
        return header.length >= 84 &&
                !new String(header, 0, 6).toLowerCase().contains("solid");
    }

    private String getFileExtension(String filename) {
        int lastDot = filename.lastIndexOf('.');
        return lastDot > 0 ? filename.substring(lastDot + 1) : "";
    }
}